package com.sunwayworld.baseline.qywx.login;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.baseline.qywx.login.bean.EnterpriseWxConf;
import com.sunwayworld.baseline.qywx.login.utils.RestUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 企业微信登录
 * @param code DTjRKWHWqJbu79OZY1XUWwGTdriXxgOsoyFQhtQRK1U
 * @return
 */

@RestController
@RequestMapping("/infra/security")
public class SecurityRest {
    private static final Logger log = LogManager.getLogger(SecurityRest.class);

    @Autowired
    @Lazy
    private QywxLimsSenderService qywxLimsSenderService;

    @RequestMapping("/qywxLogin")
    public RestResult qywxLogin(@RequestBody JSONObject jsonObject) {
        RestResult result = null;
        boolean isHasException = false;
        String qywxUserId = null;
        try {
            String fileJson = RestUtil.getJsonFromFile("enterprise_wx_conf");
            EnterpriseWxConf conf = JSONObject.parseObject(fileJson, EnterpriseWxConf.class);
            String userIdUrl = conf.getUserIdUrl();
            userIdUrl = String.format(userIdUrl, jsonObject.getString("code"));
            Map<String, Object> res = qywxLimsSenderService.sendBizRequest(userIdUrl, null, HttpMethod.GET);
            qywxUserId = (String) res.get("UserId");

        } catch (Exception e) {
            isHasException = true;
            log.error("Qywx login failed, qywxUserId:" + qywxUserId, e);
            result = RestResult.error(500, e.getMessage());
        }

        if (isHasException) {
            return result;
        }

        result = RestResult.ok();

        return result;
    }

}
